<script setup>
import bootPopup from '@/components/bootPopup.vue';
import newLoading from '@/components/newLoading/index.vue';
import Toast from "@vant/weapp/dist/toast/toast";

import { imgByteedit, editImgUpload, getImageByTaskId } from '@/api/painting'
import { getCategoryDetail } from '@/api/home'
import { imgUploadVerify } from "@/utils/auth";
import { usePaintingStore } from "@/store";

import { ref } from 'vue';
import { onLoad, onUnload } from "@dcloudio/uni-app";


const paintingStore = usePaintingStore();



// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 页面参数
const queryParams = ref({})
// 提交数据
const queryData = ref({
    prompt: '', // 文字
    promptWeight: 0.5, // 生成时长
    num: 1, // 生成张数
    model: 'DOUBAO', // 模型
    imgModel: 'img2img_e_commerce_style',
})
// 消耗算力
const expendNum = ref(0)
// 图片数量
const imgNumList = ref([])

const loading = ref(false);
const loadingRef = ref(null);

// 任务ID
const taskId = ref('')
let timer = null

// 引导层显示
const bootPopupShow = ref(false)

// 展示引导层
function onClickTitle() {
    bootPopupShow.value = true

}

// 立即生成
async function startFn() {
    clearInterval(timer);
    await verifyFn()
    loading.value = true
    await editImgUploadFn()
    imgByteeditFn()
}


// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        const data = {
            id: res.data.id,
            title: queryInfo.value.title,
            modelTypeId: queryItem.value.modelTypeId,
        }
        uni.navigateTo({
            url: `/draw/paintingResultPage/index?item=${JSON.stringify(data)}`,
        });
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        const errorMessage = res.data?.remark.split('失败原因：')[1]
        Toast.fail(errorMessage);
        loading.value = false
    }
}



// 发起生成背景任务
async function imgByteeditFn() {
    try {
        const res = await imgByteedit(queryData.value)
        paintingStore.setinstructDrawFn(queryData.value)
        taskId.value = res.data.taskId
        timer = setInterval(() => {
            getImageByTaskIdFn()
        }, 5000);
    } catch (error) {
        loading.value = false
    }
}


// 上传原图
async function editImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await editImgUpload({
                type: 11,
                orgImg: queryParams.value.imageFileUrl
            })
            queryData.value.imageFileUrl = res.orgImgUrl
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }
    })
}



// 校验方法
function verifyFn() {
    return new Promise((resolve, reject) => {
        if (!queryParams.value.imageFileUrl) {
            Toast.fail('请上传图片')
            return reject()
        } else if (!queryData.value.prompt) {
            Toast.fail('请输入描述词')
            return reject()
        }
        resolve()
    })
}



// 滑块拖动
function sliderDrag(e) {
    queryData.value.promptWeight = e.detail.value
}

// 上传图片
async function uplaodImgFn() {
    const res = await imgUploadVerify()
    queryParams.value.imageFileUrl = res
}

// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id)
    queryInfo.value = res.data
    dataConversion()
}


// 数据转换
function dataConversion() {
    queryInfo.value.categoryParam.forEach(item => {
        if (item.title === 'imgNum') {
            imgNumList.value = item.data[0].title.split(',')
            queryData.value.num = imgNumList.value[0]
        } else if (item.title === 'expendNum') {
            expendNum.value = item.data[0].title
        }
    })
}


onUnload(() => {
    clearInterval(timer);
    loading.value = false
})


onLoad((e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
    }
    getCategoryDetailFn()
})

</script>

<template>
    <div class='instructDraw'>
        <NavBar>{{ queryInfo?.title }}</NavBar>
        <div class="container">
            <div class="title_box">
                <div>上传图片</div>
                <div class="explain" @click="onClickTitle">
                    <i class="iconfont ai-icon-tishishuoming"></i>
                    玩法说明
                </div>
            </div>
            <div class="uploadImg" @click="uplaodImgFn">
                <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" mode="aspectFit" class="imgSty" alt="">
                <div class="upload_icon" v-else>
                    <i class="iconfont ai-icon-shangchuancankaotu"></i>
                    <div class="text">上传图片</div>
                </div>
            </div>

            <div class="title_box">描述词</div>
            <div class="teatarea_box">
                <textarea v-model="queryData.prompt" placeholder="请表述你想调整的位置" placeholder-class="teatareaPlaceHolder"
                    class="teatarea"></textarea>
                <!-- <div class="describe_btn" @click.stop="onClickTitle">描述示例</div> -->
            </div>
            <div class="label_box">
                <div class="label">描述词强度</div>
                <div class="value">
                    <van-slider :value="queryData.promptWeight" :step="0.1" :min="0.1" :max="1" active-color="#86CA8B"
                        bar-height="6" use-button-slot @drag="sliderDrag">
                        <template #button>
                            <div class="sliderBtn">{{ queryData.promptWeight }}</div>
                        </template>
                    </van-slider>
                </div>
            </div>
            <div class="sliderLabel">值越大，则描述词影响程度越高</div>


            <div class="title_box">选择生成张数</div>
            <div class="imgNum_box">
                <div class="imgNum" v-for="item of imgNumList" :class="{ active: item === queryData.num }"
                    @click="queryData.num = item">
                    {{ item }}
                </div>
            </div>


        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <myDrawButton :expendNum="expendNum * queryData.num" @click="startFn"></myDrawButton>
            </div>
        </div>
    </div>
    <van-toast id="van-toast"></van-toast>
    <newLoading ref="loadingRef" v-model="loading" :duration="15000" :label="['排队中，预计等待20秒']" @close="loadingClose">
    </newLoading>
    <bootPopup v-model="bootPopupShow" :title="queryInfo?.title" type="11"></bootPopup>
</template>

<style lang='scss' scoped>
.instructDraw {
    .container {
        padding: 0 30rpx;

        .title_box {
            position: relative;
            font-size: 28rpx;
            font-weight: bold;
            color: var(--a-one-text-color);
            padding-left: 30rpx;
            margin: 40rpx 0 18rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;

            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translate(0, -50%);
                width: 12rpx;
                height: 18rpx;
                background: var(--a-main-color);
                border-radius: 6rpx;
            }

            .text {
                font-size: 24rpx;
                font-weight: normal;
            }

            .explain {
                font-size: 24rpx;
                color: var(--a-two-text-color);
                font-weight: normal;
                display: flex;
                align-items: center;
                gap: 10rpx;

                .iconfont {
                    font-size: 24rpx;
                    color: var(--a-two-text-color);
                }
            }
        }


        .uploadImg {
            box-sizing: border-box;
            height: 356rpx;
            padding: 10rpx;
            background: var(--a-main-box-bg-color);
            border-radius: 20rpx;
            margin-top: 22rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            .imgSty {
                width: 100%;
                height: 100%;
                border-radius: 20rpx;
            }

            .upload_icon {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                gap: 20rpx;

                .iconfont {
                    font-size: 42rpx;
                    color: var(--a-main-color);
                }

                .text {
                    font-size: 22rpx;
                    color: var(--a-three-text-color);
                }
            }
        }

        .teatarea_box {
            position: relative;
            height: 199rpx;
            margin-top: 23rpx;

            .teatarea {
                box-sizing: border-box;
                width: 100%;
                height: 100%;
                color: var(--a-one-text-color);
                background: var(--a-main-box-bg-color);
                border-radius: 24rpx;
                padding: 20rpx 24rpx;

                ::v-deep.teatareaPlaceHolder {
                    font-size: 28rpx;
                    color: var(--a-three-text-color);
                }
            }

            .describe_btn {
                width: 124rpx;
                height: 43rpx;
                background: #3E3972;
                border-radius: 22rpx;
                border: 1rpx solid var(--a-two-text-color);
                font-size: 22rpx;
                color: var(--a-one-text-color);
                display: flex;
                align-items: center;
                justify-content: center;
                position: absolute;
                right: 20rpx;
                bottom: 20rpx;
                z-index: 2;
            }
        }

        .label_box {
            display: flex;
            align-items: center;
            gap: 30rpx;
            margin-top: 40rpx;

            .label {
                flex-shrink: 0;
                font-size: 26rpx;
                color: var(--a-one-text-color);
            }

            .value {
                flex: 1;

                .sliderBtn {
                    width: 50rpx;
                    height: 50rpx;
                    font-size: 26rpx;
                    border-radius: 50%;
                    color: var(--a-main-color);
                    background-color: var(--a-one-text-color);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
            }
        }

        .sliderLabel {
            box-sizing: border-box;
            font-size: 22rpx;
            color: var(--a-two-text-color);
            margin-top: 30rpx;
            padding-left: 250rpx;

        }

        .imgNum_box {
            display: flex;
            align-items: center;
            margin-top: 26rpx;

            .imgNum {
                width: 84rpx;
                height: 84rpx;
                line-height: 80rpx;
                border-radius: 13rpx;
                background: var(--a-main-box-bg-color);
                margin-right: 18rpx;
                text-align: center;
                border: 4rpx solid transparent;
                color: var(--a-one-text-color);

                &.active {
                    color: var(--a-main-color);
                    border: 4rpx solid var(--a-main-color);
                }
            }
        }


    }

    .footer {
        .footer_placeholder {
            height: 176rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 176rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 28rpx 30rpx 0;

            .create_btn {
                height: 86rpx;
                background: var(--a-main-color);
                border-radius: 44rpx;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;

                .create_btn_title {
                    font-size: 32rpx;
                    color: var(--a-one-text-color);
                }

                .create_btn_label {
                    font-size: 20rpx;
                    color: var(--a-one-text-color);
                }
            }
        }
    }
}
</style>